package mini.ideashare.cms.controller;

import com.alibaba.fastjson.JSON;
import mini.ideashare.cms.base.BaseResponse;
import mini.ideashare.cms.base.PageData;
import mini.ideashare.cms.manager.UserManager;
import mini.ideashare.cms.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lixiang
 * @CreateTime 2018/10/27
 **/
@Controller
public class UserController extends AbstractBaseController {
    @Autowired
    private UserManager userManager;

    @GetMapping("/user/query")
    @ResponseBody
    public BaseResponse<PageData<User>> queryUser(User user, Integer pageIndex , Integer pageSize){

        List<User> users = userManager.queryUser(user, pageIndex, pageSize);
        Long totalCount = userManager.countUser(user);

        pageIndex = pageIndex == null?1:pageIndex;
        pageSize = pageSize == null?20:pageSize;
        return  BaseResponse.assemblePageResponse(users,totalCount,pageIndex,pageSize);
    }

    @PostMapping("/user/register")
    @ResponseBody
    public BaseResponse<String> saveItem(User user){
        BaseResponse<String> baseResponse = new BaseResponse<>();
        try {
            userManager.saveUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse.setSuccess(false);
            baseResponse.setMessage("用户名重复");
            return baseResponse;
        }
        baseResponse.setData("OK");
        return  baseResponse;
    }

    @GetMapping("/user/list")
    @ResponseBody
    public String listItem(User user, Integer pageNumber , Integer pageSize){

        Map<String,Object> map  = new HashMap<>();

        List<User> users = userManager.queryUser(user, pageNumber, pageSize);
        Long totalCount = userManager.countUser(user);
        map.put("total",totalCount);
        map.put("rows",users);
        return JSON.toJSONString(map);
    }
    
    @GetMapping("/user/login")
    @ResponseBody
    public BaseResponse<User> listItem(User user){

        if(StringUtils.isEmpty(user.getUserName())|| StringUtils.isEmpty(user.getPassword())){
            return assembleResponse(false,"100","用户名或密码错误");
        }
        List<User> users = userManager.queryUser(user, 1, 1);
        if(users!=null && users.size()>0){
            return assembleResponse(users.get(0));
        }else{
            return assembleResponse(false,"100","用户名或密码错误");

        }
    }



}
